<script setup>
import { ref, onMounted } from 'vue'
import ListHeader from '@/components/list-header.vue'
import {
  getGoodsListApi,
  checkApi,
  deleteApi,
  changestatusApi,
  deleteAllApi,
  createApi,
  updateApi,
  restoreApi,
  destroyApi
} from '@/api/goods'
import { toast } from '@/utils/elnotification'
import FromDrawer from '@/components/from-drawer.vue'
import ChooseImage from '@/components/choose-image.vue'
import Banners from './banners.vue'
import Content from './content.vue'

// 订单类型：all全部，checking审核中，saling出售中，off已下架，min_stock库存预警，delete回收站
const tabsList = [
  { label: '全部', name: 'all' },
  { label: '审核中', name: 'checking' },
  { label: '出售中', name: 'saling' },
  { label: '已下架', name: 'off' },
  { label: '库存预警', name: 'min_stock' },
  { label: '回收站', name: 'delete' }
]

//总页数
const total = ref(0)

//当前页数
const currentPage = ref(1)

//页面loading
const loading = ref(false)

//默认激活tabs
const activeName = ref('all')

//tabs切换
const onTabChange = (val) => {
  activeName.value = val
  getGoodsList()
}

// 搜索栏
const searchForm = ref({
  title: '',
  category_id: null
})

//商品分类
const catagoryList = ref([])

//商品分类显示条件
const isShowCategorySelect = ref(false)

//搜索
const onSearch = () => {
  getGoodsList(1)
}

//重置
const onReset = () => {
  //清空搜索栏
  searchForm.value = {
    title: '',
    category_id: null
  }
  //重新获取数据
  getGoodsList(1)
}

//table数据
const tableData = ref([])

//获取tableData数据
const getGoodsList = async (p = null) => {
  //传递进来的页码
  if (typeof p === 'number') {
    currentPage.value = p
  }

  //开启页面加载效果
  loading.value = true

  try {
    //调用接口
    const res = await getGoodsListApi(currentPage.value, {
      tab: activeName.value,
      title: searchForm.value.title,
      category_id: searchForm.value.category_id
    })
    //赋值页面数
    total.value = res.totalCount
    //赋值商品分类
    catagoryList.value = res.cates
    //赋值tableData
    tableData.value = res.list
  } catch (error) {
  } finally {
    //关闭页面加载效果
    loading.value = false
  }
}

//审核
const onChecked = async (val, num) => {
  try {
    await checkApi(val.id, num)
    toast('操作成功')
    //重新获取数据
    getGoodsList(1)
  } catch (error) {}
}

//删除商品
const onDelete = async (row) => {
  console.log(row.id)
  try {
    await deleteApi(row.id)
    toast('删除成功')
    getGoodsList()
  } catch (error) {
    toast('删除失败')
  }
}

//存储全选/多选的数据id
const ids = ref([])

//全选/多选事件
const onSelectionChange = (val) => {
  ids.value = val.map((item) => item.id)
}

//上架/下架
const onChangeStatus = async (status) => {
  if (ids.value.length === 0) return toast('请选择所需要操作的数据', 'error')

  try {
    await changestatusApi(ids.value, status)
    toast('操作成功')
    getGoodsList(1)
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    ids.value = []
  }
}

//批量删除
const onDeleteAll = async () => {
  if (ids.value.length === 0) return toast('请选择所需要操作的数据', 'error')
  try {
    await deleteAllApi(ids.value)
    toast('批量删除成功')
    getGoodsList(1)
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    ids.value = []
  }
}

//抽屉组件
const fromDrawerRef = ref(null)

//抽屉组件标题
const formDrawertitle = ref('')

//抽屉表单
const formDrawer = ref({
  title: '', //商品名称
  category_id: null, //商品分类
  cover: '', //商品封面
  desc: '', //商品描述
  unit: '', //商品单位
  stock: 200, //总库存
  min_stock: 10, //库存预警
  status: 1, //是否上架 0仓库1上架
  stock_display: 1, //库存显示 0隐藏1禁用
  min_price: 1, //最低销售价
  min_oprice: 100 //最低原价
})

//新增
const onCreate = () => {
  //设置标题
  formDrawertitle.value = '新增'

  //还原表单
  formDrawer.value = {
    title: '', //商品名称
    category_id: null, //商品分类
    cover: '', //商品封面
    desc: '', //商品描述
    unit: '', //商品单位
    stock: 200, //总库存
    min_stock: 10, //库存预警
    status: 1, //是否上架 0仓库1上架
    stock_display: 1, //库存显示 0隐藏1禁用
    min_price: 1, //最低销售价
    min_oprice: 100 //最低原价
  }

  changeId.value = 0

  //显示抽屉
  fromDrawerRef.value.open()
}

//存储修改的id
const changeId = ref(0)

//修改
const onUpdata = (row) => {
  //设置标题
  formDrawertitle.value = '修改'
  const {
    id,
    title,
    category_id,
    cover,
    desc,
    unit,
    stock,
    min_stock,
    status,
    stock_display,
    min_price,
    min_oprice
  } = row

  formDrawer.value = {
    title,
    category_id,
    cover,
    desc,
    unit,
    stock,
    min_stock,
    status,
    stock_display,
    min_price,
    min_oprice
  }

  changeId.value = id

  //显示抽屉
  fromDrawerRef.value.open()
}

//确认
const onSubmit = async () => {
  //打开加载
  fromDrawerRef.value.showLoading()

  if (changeId.value === 0) {
    try {
      await createApi({ ...formDrawer.value })
      toast('新增成功')
      getGoodsList(1)
    } catch (error) {
      toast('新增失败', 'error')
    } finally {
      //关闭加载
      fromDrawerRef.value.hideLoading()
    }
  } else {
    try {
      await updateApi(changeId.value, { ...formDrawer.value })
      toast('编辑成功')
      getGoodsList(1)
    } catch (error) {
      toast('编辑失败', 'error')
    } finally {
      //关闭加载
      fromDrawerRef.value.hideLoading()
    }
  }
}

//恢复商品
const onCecover = async () => {
  if (ids.value.length === 0) return toast('请选择所需要操作的数据', 'error')
  try {
    await restoreApi(ids.value)
    toast('恢复成功')
    getGoodsList(1)
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    ids.value = []
  }
}

//彻底删除
const onCompletely = async () => {
  if (ids.value.length === 0) return toast('请选择所需要操作的数据', 'error')
  try {
    await destroyApi(ids.value)
    toast('彻底删除成功')
    getGoodsList(1)
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    ids.value = []
  }
}

//轮播图节点
const bannersRef = ref(null)

//轮播图设置
const onSetBanners = (row) => {
  bannersRef.value.show(row)
}

//content节点
const contentRef = ref(null)
const onSetContent = (row) => {
  contentRef.value.show(row)
}

onMounted(() => {
  getGoodsList()
})
</script>

<template>
  <div>
    <!-- tab切换 -->
    <el-tabs v-model="activeName" @tab-change="onTabChange">
      <el-tab-pane
        :label="item.label"
        :name="item.name"
        v-for="(item, index) in tabsList"
        :key="index"
      ></el-tab-pane>
    </el-tabs>
    <el-card shadow="never" class="border-0">
      <!-- 搜索 -->
      <el-form :model="searchForm" label-width="7.5rem" ref="searchFormRef">
        <el-row :gutter="20">
          <el-col :span="8" :offset="0">
            <el-form-item label="商品名称">
              <el-input v-model="searchForm.title" placeholder="请输入商品名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="商品分类" v-if="isShowCategorySelect">
              <el-select v-model="searchForm.category_id" placeholder="请选择商品分类">
                <el-option
                  v-for="item in catagoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <div class="flex items-center justify-end">
              <el-button type="primary" @click="onSearch">搜索</el-button>
              <el-button @click="onReset">重置</el-button>
              <el-button type="primary" text @click="isShowCategorySelect = !isShowCategorySelect">
                {{ isShowCategorySelect ? '收起' : '展开' }}
                <el-icon>
                  <component :is="isShowCategorySelect ? 'ArrowUp' : 'ArrowDown'"></component>
                </el-icon>
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- 新增/删除/上下架/刷新 -->
      <ListHeader
        :delete="activeName !== 'delete'"
        :soldout="activeName === 'all' || activeName === 'saling'"
        :putaway="activeName === 'all' || activeName === 'off'"
        :recover="activeName === 'delete'"
        :completely="activeName === 'delete'"
        @putaway="onChangeStatus(1)"
        @soldout="onChangeStatus(0)"
        @deleteAll="onDeleteAll"
        @refresh="getGoodsList"
        @create="onCreate"
        @recover="onCecover"
        @completely="onCompletely"
      ></ListHeader>
      <!-- 表单部分 -->
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="onSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="date" label="商品" width="270">
          <template #default="{ row }">
            <div class="flex items-start">
              <el-avatar shape="square" :size="50" fit="cover" :src="row.cover" />
              <div class="ml-2">
                <p>{{ row.title }}</p>
                <p class="text-rose-500">
                  ￥{{ row.min_price }} <span class="text-[#dcdfe6] mx-1">|</span>
                  <span class="text-gray-500 text-xs">￥{{ row.min_oprice }}</span>
                </p>
                <p class="text-xs mb-1 text-gray-400">
                  分类：{{ row.category ? row.category.name : '未分类' }}
                </p>
                <p class="text-xs text-gray-400">创建时间：{{ row.create_time }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sale_count" label="实际销量" align="center" />
        <el-table-column prop="" label="商品状态" align="center">
          <template #default="{ row }">
            <el-tag type="success" size="small" v-if="row.status === 1">上架</el-tag>
            <el-tag type="danger" size="small" v-if="row.status === 0">仓库</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="审核状态"
          align="center"
          width="150"
          v-if="activeName !== 'delete'"
        >
          <template #default="{ row }">
            <div>
              <div v-if="row.ischeck == 0">
                <el-button type="success" plain size="small" @click="onChecked(row, 1)"
                  >审核通过</el-button
                >
                <el-button
                  style="margin-left: 0"
                  class="my-2"
                  @click="onChecked(row, 2)"
                  type="danger"
                  plain
                  size="small"
                  >审核拒绝</el-button
                >
              </div>
              <p v-else>{{ row.ischeck == 1 ? '通过' : '拒绝' }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="总库存" align="center" />
        <el-table-column label="操作" width="400" fixed="right">
          <template #default="{ row }">
            <div class="flex" v-if="activeName !== 'delete'">
              <el-button text type="primary" size="small" @click="onUpdata(row)">修改</el-button>
              <el-button
                @click="toast('功能未开放', 'error')"
                text
                type="danger"
                size="small"
                :type="
                  (row.sku_type == 0 && !row.sku_value) ||
                  (row.sku_type == 1 && !row.goods_skus.length)
                    ? 'danger'
                    : 'primary'
                "
                >商品规格</el-button
              >
              <el-button
                text
                :type="row.goods_banner.length == 0 ? 'danger' : 'primary'"
                size="small"
                @click="onSetBanners(row)"
                >设置轮播图</el-button
              >

              <el-button
                text
                :type="row.content ? 'primary' : 'danger'"
                size="small"
                @click="onSetContent(row)"
                >商品详情</el-button
              >
              <el-popconfirm
                title="是否要删除该商品？"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @confirm="onDelete(row)"
                ><template #reference>
                  <el-button text type="primary" size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div v-else>暂无操作</div>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex justify-center justify-center mt-5">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          @current-change="getGoodsList"
          :current-page="currentPage"
        />
      </div>
    </el-card>
    <!-- 抽屉 -->
    <FromDrawer ref="fromDrawerRef" :title="formDrawertitle" @submit="onSubmit">
      <el-form :model="formDrawer" label-width="7.5rem">
        <el-form-item label="商品名称">
          <el-input v-model="formDrawer.title" placeholder="请输入商品名称，不吃超过60个字符" />
        </el-form-item>
        <el-form-item label="封面">
          <ChooseImage v-model:url="formDrawer.cover"></ChooseImage>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="formDrawer.category_id" placeholder="请选择商品分类">
            <el-option
              v-for="item in catagoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="formDrawer.desc" placeholder="选填,商品卖点简述" />
        </el-form-item>
        <el-form-item label="商品单位">
          <el-input v-model="formDrawer.unit" placeholder="请输入商品单位" />
        </el-form-item>
        <el-form-item label="总库存">
          <el-input v-model="formDrawer.stock" placeholder="请输入库存数">
            <template #append>{{ formDrawer.unit ? formDrawer.unit : '件' }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="库存预警">
          <el-input v-model="formDrawer.min_stock" placeholder="请输入库存预警数">
            <template #append>{{ formDrawer.unit ? formDrawer.unit : '件' }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="最低销售价">
          <el-input v-model="formDrawer.min_price" placeholder="请输入最低销售价">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="最低原价">
          <el-input v-model="formDrawer.min_oprice" placeholder="请输入最低原价价">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="库存显示">
          <el-radio-group v-model="formDrawer.stock_display">
            <el-radio :label="1" border>是</el-radio>
            <el-radio :label="0" border>否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否上架">
          <el-radio-group v-model="formDrawer.status">
            <el-radio :label="1" border>立即上架</el-radio>
            <el-radio :label="0" border>放入仓库</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </FromDrawer>
    <!-- 轮播图 -->
    <Banners ref="bannersRef" @reLoadData="getGoodsList"></Banners>
    <Content ref="contentRef" @reLoadData="getGoodsList"></Content>
  </div>
</template>

<style scoped></style>
